package framework.controller;

import java.awt.event.*;
import framework.utils.*;
import framework.event.CustomEvent;
import framework.gui.*;
import framework.model.*;

public class LoginController extends ServerController {

	/**********************
	 *** GLOBAL METHODS ***
	 *********************/
	
	/**
	 * Initialize controller
	 * @method LoginController (Constructor)
	 * @param <Model> model
	 */
	public LoginController(LoginModel model) {
		super(model);
		this.init();
	};

	private void init() { 
		//TODO fill
	};

	@Override
	public void actionPerformed(ActionEvent e) {
		switch(e.getActionCommand()){
			case "OK" :
				//LOGIN SUCCESS
				this.handleUserResponse();
			break;
			case "ERR" :
				//LOGIN FAILURE
				System.out.println("Failure");
			break;
		};
	};
	
	@Override
	public LoginModel getModel() {
		return (LoginModel) super.getModel();
	};
	
	/**********************
	 *** HANDLE METHODS ***
	 *********************/
	
	/**
	 * Handle login form request
	 * @method handleLoginRequest
	 * @param <String>  username
	 * @param <String>  serverURI
	 */
	public void handleLoginRequest(String username, String serverURI) {
		String[] serverParts = serverURI.split(":");
		if(serverParts.length == 2) {
			//GameServer-host, -port
			String serverHost = serverParts[0];
			int serverPort = Integer.parseInt(serverParts[1]);
			//Make connection with GameServer
			if(super.setSocket(serverHost, serverPort)) {
				super.initialize();
				super.setCurrentListener(this);
				super.setThread(new GameServerListener());
				super.setThread(new CommandListener());
				super.setThread(new InputReader());
				this.handleUserRequest(username);
			};
		};
	};
	
	/**
	 * Handle user login request
	 * @method handleUserRequest
	 * @param <String> username
	 */
	private void handleUserRequest(String username) {
		if(username != "") {
			//If request not already fired
			this.getModel().setUsername(username);
			if(super.setStackValue("LOGIN")) {
				super.sendCommand("login " + username);
			};
		};
	};
	
	/**
	 * @method handleLoginSuccessRequest
	 */
	private void handleUserResponse() {
		UserPreferences.setProperty("username", this.getModel().getUsername());
		this.getModel().setLoggedIn(true);
	};
	
	/**
	 * @method handleLobbyRequest
	 */
	public void handleLobbyRequest() {
		new LobbyGUI();
	};
	
}
